package com.ai.dmc.utils.springbean;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 
 * <p>Title: SystemServiceLocator.java</p>
 * <p>Description: 取得Spring配置中的bean的工具类，使用时需要先调用getWebInstance（ServletContext context）初始化</p>
 * <p>Copyright: Copyright (c) 2009</p>
 * <p>Company: 亚信科技（中国）有限公司</p>
 * @author chenhui2
 * @version 1.0 
 *
 */
public class SystemServiceLocator {
	
	private static Log log = LogFactory.getLog(SystemServiceLocator.class);
	
	private static SystemServiceLocator instance;
	private static BeanFactory factory;

	/**
	 * 构造函数
	 */
	private SystemServiceLocator() {
		factory = ContextLoader.getCurrentWebApplicationContext();
	}
	/**
	 * 构造函数
	 * @param context
	 */
	private SystemServiceLocator(ServletContext context) {
		try {
			factory = WebApplicationContextUtils
					.getWebApplicationContext(context);
			log.info("--------->>SystemServiceLocator init successful by web...");
		} catch (Exception e) {
			log.debug(e);
		}
	}

	/**
	 * 构造一个依赖web环境的Service工厂实例
	 * @param context
	 * @return
	 * SystemServiceLocator
	 *
	 */
	public static SystemServiceLocator getWebInstance(ServletContext context) {
		if (instance == null) {
			instance = new SystemServiceLocator(context);
		}
		return instance;
	}

	/**
	 * 构造一个不依赖web环境的Service工厂实例
	 * @return
	 * SystemServiceLocator
	 *
	 */
	public static SystemServiceLocator getInstance() {
		if (instance == null) {
			instance = new SystemServiceLocator();
		}
		return instance;
	}

	/**
	 * 
	 * 根据serviceId取服务类
	 * 
	 * @param serviceId
	 * @return Object
	 * @throws Exception
	 *
	 */
	public Object getService(String serviceId) throws Exception {
		try {
			Object obj = null;
			if (factory != null && serviceId != null
					&& serviceId.length() > 1)
				obj = factory.getBean(serviceId);
			return obj;
		} catch (Exception e) {
			log.debug("------Get bean by  name [" + serviceId + "] error !");
			throw new Exception("---------Get bean by  name [" + serviceId + "] error !");
		}
	}
}